package ftp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

import ftp.datalay.FTP_Data;
import ftp.datalay.FTP_Response;

public class ClientConnection implements IClient{

	private BufferedWriter writer;
	private BufferedReader reader;
	private FTP_Data ftpData = null;
	private Socket socket = null;
	
	public ClientConnection(String host, int port){
		ftpData = new FTP_Data(host, port);
	}

	@Override
	public void open() throws IOException {
		socket = new Socket(ftpData.getHost(), ftpData.getPort());
		writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
		reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		
	}

	@Override
	public FTP_Response send(String command) throws IOException {
		writer.write(command+ "\r\n");
		writer.flush();
		return getReply();
	}

	@Override
	public FTP_Response getReply() throws IOException {
		StringBuffer sb = new StringBuffer();
        String line = null;
        
        do{
        	line = reader.readLine();
        	sb.append(line).append("\r\n");
        	if(line == null || line.length() < 5 ) throw new IOException("illegalt FTP svar" + line);
        }while(line == null);

        return new FTP_Response(sb.toString());
	}

	@Override
	public void close() throws IOException {
		socket.close();
		writer.close();
		reader.close();
		
	}
	
}
